18. 解决方案:GROUP BY(第二部分)

解决方案:GROUP BY(第二部分)

  1. 对于每个客户,确定他们在订单中购买的每种纸张的平均数额。结果应该有四列:客户 名称 一列,每种纸张类型的平均数额一列。
SELECT a.name, AVG(o.standard_qty) avg_stand, AVG(gloss_qty) avg_gloss, AVG(poster_qty) avg_post
FROM accounts a
JOIN orders o
ON a.id = o.account_id
GROUP BY a.name;
  1. 对于每个客户,确定在每个订单中针对每个纸张类型的平均消费数额。结果应该有四列:客户 名称 一列,每种纸张类型的平均消费数额一列。
SELECT a.name, AVG(o.standard_amt_usd) avg_stand, AVG(gloss_amt_usd) avg_gloss, AVG(poster_amt_usd) avg_post
FROM accounts a
JOIN orders o
ON a.id = o.account_id
GROUP BY a.name;
  1. 确定在 web_events 表格中每个 销售代表 使用特定 渠道 的次数。最终表格应该有三列: 销售代表的名称 渠道 和发生次数。按照最高的发生次数在最上面对表格排序。
SELECT s.name, w.channel, COUNT(*) num_events
FROM accounts a
JOIN web_events w
ON a.id = w.account_id
JOIN sales_reps s
ON s.id = a.sales_rep_id
GROUP BY s.name, w.channel
ORDER BY num_events DESC;
  1. 确定在 web_events 表格中针对每个 地区 特定 渠道 的使用次数。最终表格应该有三列: 区域名称 渠道 和发生次数。按照最高的发生次数在最上面对表格排序。
SELECT r.name, w.channel, COUNT(*) num_events
FROM accounts a
JOIN web_events w
ON a.id = w.account_id
JOIN sales_reps s
ON s.id = a.sales_rep_id
JOIN region r
ON r.id = s.region_id
GROUP BY r.name, w.channel
ORDER BY num_events DESC;